package nl.wubinator.aeve.xmlconverters.limited;

import nl.wubinator.aeve.models.limited.characters.Character;
import nl.wubinator.aeve.models.limited.characters.Characters;
import nl.wubinator.aeve.xmlconverters.ConverterBase;
import nl.wubinator.aeve.xmlconverters.limited.parsers.CharacterParser;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import android.util.Log;

/**
 * This class will parse the XML retrieved from the character selection of the
 * eve api to a <code>Characters</code> class.
 * 
 * @author Rick
 */
public class CharactersSelectionConverter extends ConverterBase {
	// Used to define what elements we are currently in
	private boolean inCurrentTime = false;
	private boolean inCachedUntil = false;
	private boolean inCharactersRowSet = false;

	// Character object to use for temporary storage
	private Character currentCharacter;

	// The complete characters object that will be filled in this converter
	private Characters characters = new Characters();

	public void startElement(String uri, String name, String qName,
			Attributes atts) {
		if (name.trim().equals("currentTime"))
			inCurrentTime = true;
		else if (name.trim().equals("cachedUntil"))
			inCachedUntil = true;
		else if (name.trim().equals("rowset")) {
			String rowsetAttributes = atts.getValue("name");
			if (rowsetAttributes.equals("characters")) {
				inCharactersRowSet = true;
			}
		} else if (name.trim().equals("row")) {
			if (inCharactersRowSet) {
				this.currentCharacter = new Character();
				CharacterParser.parseAttributes(atts, currentCharacter);
			}
		}
	}

	public void endElement(String uri, String name, String qName)
			throws SAXException {
		if (name.trim().equals("currentTime"))
			inCurrentTime = false;
		else if (name.trim().equals("cachedUntil"))
			inCachedUntil = false;
		else if (name.trim().equals("row")) {
			// When the row is closed a Character class has been fully created
			// add it to the characters and create a new current Character
			characters.addCharacter(currentCharacter);
		}

		if (name.trim().equals("eveapi")) {
			setResult(characters);
		}
	}

	public void characters(char ch[], int start, int length) {
		String chars = (new String(ch).substring(start, start + length));

		try {
			if (chars.equals("\n"))
				return;

			if (inCurrentTime) {
				this.characters.setCurrentTime(chars);
			} else if (inCachedUntil) {
				this.characters.setCachedUntil(chars);
			}
		} catch (Exception e) {
			Log.e("Reading XML error", e.getMessage());
		}
	}
}
